<template>
  <div>
    <el-menu :default-active="type" class="el-menu-demo" mode="horizontal" @select="handleSelect">
<!--      <el-menu-item  index="goodsName">产品类别</el-menu-item>-->
      <el-menu-item  index="brandName">生产厂家</el-menu-item>
    </el-menu>
    <!-- :tree-config="{transform:true,rowField:'categoryId', parentField: 'parentId',indent:20,expandAll:true}" -->

    <!--数据列表-->
    <div class="table-container">
      <vxe-grid ref='xGrid' v-if="this.type=='goodsName'"
                v-bind="gridOptions" size="mini" :loading="listLoading">
        <template #form>
          <!--搜索-->
          <div>
            <div style="background: #f5f7fa;padding:15px 15px 0 15px;border:1px solid #EBEEF5;border-bottom:0.5px solid #EBEEF5;">
              <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
                <el-form-item label="品名名称：" >
                  <el-input v-model="listQuery.categoryName" clearable placeholder="请输入关键词"></el-input>
                </el-form-item>

                <el-form-item>
                  <el-button
                    @click="handleSearchList()"
                    type="primary">
                    查询
                  </el-button>
                  <el-button
                    @click="syncData"
                    :loading="syncLoading"
                    type="primary">
                    同步ERP
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </template>
        <template #toolbar_buttons>
        </template>
        <template #num1_default="{ row, rowIndex }">
          <span>{{ row.isEnable | fifIsShow}}</span>
        </template>
        <template #num3_default="{ row, rowIndex }">
          <el-button style="margin-right:10px;" type="text" size="small"  @click="showPop('edit',row)">编辑</el-button>
          <el-button style="margin-right:10px;" type="text" size="small" @click="changeState(row)"><span>{{ row.isEnable ? '禁用' : '启用' }}</span></el-button>
        </template>

      </vxe-grid>

      <vxe-grid ref='xGrid2' v-else-if="this.type=='brandName'" v-bind="gridOptions2" size="mini" :loading="listLoading2"  >
        <template #form>
          <!--搜索-->
          <div>
            <div style="background: #f5f7fa;padding:15px 15px 0 15px;border:1px solid #EBEEF5;border-bottom:0.5px solid #EBEEF5;">
              <el-form :inline="true" :model="listQuery2" size="mini" label-width="100px">
                <el-form-item label="厂家名称：" >
                  <el-input
                    clearable
                    v-model="listQuery2.brandName"
                    placeholder="请输入厂家名称"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button
                    @click="handleSearchList()"
                    type="primary">
                    查询
                  </el-button>
                  <el-button
                    @click="showPop2('add')"
                    type="primary">
                    新增
                  </el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </template>
        <template #pager>
          <div style="overflow: hidden">
            <div class="pagination-container" style="float:right;">
              <el-pagination
                background
                @size-change="handleSizeChange2"
                @current-change="handleCurrentChange2"
                layout="total, sizes,prev, pager, next,jumper"
                :current-page.sync="listQuery2.pageNum"
                :page-size="listQuery2.pageSize"
                :page-sizes="[10,15,20,50,100,200]"
                :total="count2">
              </el-pagination>
            </div>
          </div>
        </template>
        <template #toolbar_buttons>
        </template>
        <template #num2_default="{ row, rowIndex }">
          <span>{{ row.isEnable | fifIsShow}}</span>
        </template>
        <template #num3_default="{ row, rowIndex }">
          <el-button style="margin-right:10px;" type="text" size="small"  @click="showPop2('edit',row)">编辑</el-button>
          <el-button style="margin-right:10px;" type="text" size="small" @click="changeState2(row)"><span>{{ row.isEnable ? '禁用' : '启用' }}</span></el-button>
        </template>

      </vxe-grid>
    </div>

    <el-dialog
      :title="sendForm.categoryId ? '编辑品类' : '新增品类'"
      :visible.sync="dialogVisible"
      :beforeClose="handleClose"
      width="400px">
      <el-form size="mini" :model="sendForm" label-width="120px"  ref="sendForm" :rules="rules">
        <el-form-item label="品类名称：" prop="categoryName">
          <el-input v-model="sendForm.categoryName" maxLength="20" style="width:194px"></el-input>
        </el-form-item>

        <el-form-item label="父级：" >
          <el-select
            v-model="sendForm.parentId"
            filterable
            placeholder="不选为一级品类"
            clearable
          >
            <el-option
              v-for="item in categoryList"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序：" prop="sortOrder">
            <el-input  v-model="sendForm.sortOrder" type="number" style="width:194px"></el-input>
        </el-form-item>
        <el-form-item label="状态：" prop="isEnable">
          <el-radio-group v-model="sendForm.isEnable">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
      </span>
    </el-dialog>

    <!--厂家-->
    <el-dialog
      :title="sendForm.brandId ? '编辑厂家' : '新增厂家'"
      :visible.sync="dialogVisible2"
      :beforeClose="handleClose2"
      width="450px">
      <el-form size="mini" :model="sendForm2" label-width="120px"  ref="sendForm2" :rules="rules2">
        <el-form-item label="厂家名称：" prop="brandName">
          <el-input v-model="sendForm2.brandName" style="width:120px"></el-input>
        </el-form-item>

        <el-form-item label="排序：">
          <el-input style="width:120px" v-model="sendForm2.sortOrder" type="number"></el-input>
        </el-form-item>
        <el-form-item label="状态：" prop="isEnable">
          <el-radio-group v-model="sendForm2.isEnable">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose2">取 消</el-button>
          <el-button type="primary" @click="handleConfirm2" :loading="btnLoading2">确 定</el-button>
      </span>
    </el-dialog>



  </div>
</template>

<script>
import {materialClassTree,getBrandList,saveBrand,saveCategory,syncMaterialClass} from '@/api/allInLine/goods'

import store from '@/store'
import { mapGetters } from 'vuex'
import { Message } from 'element-ui';

const defaultListQuery={
  categoryName:'',
  isEnable:''
};
const defaultListQuery2={
  pageSize:10,
  pageNum:1,
  brandName : "",//客户名称
};
const defaultSendForm= {
  "categoryId": 0, //分类ID
  "parentId": "", //父级（默认传0）
  "categoryName": "", //分类名称
  "isEnable": 1, //是否启用(1是，0否)
  "sortOrder": 0, //排序值
}
const defaultSendForm2= {
  "brandId": "0", //厂家ID
  "brandName": "", //厂家名称
  "isEnable": 1, //是否启用(1是，0否)
  "sortOrder": 0, //排序值
}

export default {
  name: "index",
  data(){
    return{
      roles:store.getters.roles ? store.getters.roles : [],
      names:store.getters.name ? store.getters.name : '',
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      listQuery2: JSON.parse(JSON.stringify(defaultListQuery2)),
      sendForm:JSON.parse(JSON.stringify(defaultSendForm)),
      sendForm2:JSON.parse(JSON.stringify(defaultSendForm2)),
      btnLoading2:false,
      btnLoading:false,
      listLoading:false,
      listLoading2:false,
      dialogVisible2:false,
      dialogVisible:false,
      type:'brandName',
      rules2:{
        brandName:[{required: true, message: '此项必填', trigger: 'blur'}],
        isEnable:[{required: true, message: '此项必填', trigger: 'change'}],
      },
      count:0,
      rules:{
        categoryName:[{required: true, message: '此项必填', trigger: 'blur'}],
        isEnable:[{required: true, message: '此项必填', trigger: 'change'}],
      },
      gridOptions:{
        loading:this.listLoading,
        border: true,
        id: 'goodsName',
        align:'center',
        autoResize:true,
        minHeight:300,
        maxHeight:window.innerHeight-260,
        size:'mini',
        rowConfig: {
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
        },
        checkboxConfig:{
          reserve:true
        },
        treeConfig:{
          children: 'children',
          accordion: false,
          trigger:'cell'
        },
        toolbarConfig: {
          zoom: true,
          custom: true,
          slots: {
            buttons: 'toolbar_buttons',
          }
        },
        columns: [
          {
            field: 'categoryName',
            title: '品类名称',
            width: 180,
            treeNode:"true",
            align:'left',
            headerAlign:'center'
          },
          {
            field: 'sortOrder',
            title: '排序',
            width: 150,
          },
          {
            field: 'createTime',
            title: '创建时间',
            width: 150,
          },
          {
            field: 'updatedAt',
            title: '更新时间',
            width: 150,
          },
          {
            field: 'isEnable',
            title: '状态',
            width: 150,
            slots:{
              default:'num1_default'
            }
          },
          {
            field: 'setting',
            title: '操作',
            width: 150,
            fixed:'right',
            slots: {
              // 使用插槽模板渲染
              default: 'num3_default',
            }
          },
        ],
        data:[],
      },
      gridOptions2:{
        loading:this.listLoading2,
        border: true,
        id: 'attributeList',
        align:'center',
        autoResize:true,
        minHeight:300,
        size:'mini',
        rowConfig: {
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
        },
        checkboxConfig:{
          reserve:true
        },
        toolbarConfig: {
          zoom: true,
          custom: true,
          slots: {
            buttons: 'toolbar_buttons',
          }
        },
        columns: [
          {
            field: 'brandName',
            title: '厂家名称',
            width: 150,
          },
          {
            field: 'sortOrder',
            title: '排序',
            width: 100,
          },
          {
            field: 'isEnable',
            title: '状态',
            width: 100,
            slots:{
              default:'num2_default'
            }
          },
          {
            field: 'createdAt',
            title: '创建时间',
            width: 150,
          },
          {
            field: 'updatedAt',
            title: '更新时间',
            width: 180,
          },
          {
            field: 'setting',
            title: '操作',
            width: 150,
            fixed:'right',
            slots: {
              // 使用插槽模板渲染
              default: 'num3_default',
            }
          },
        ],
        data:[],
      },
      count2:0,
      categoryList:[],
      syncLoading:false

    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  watch: {
    categoryName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getListData();
  },
  filters: {
    fifIsShow(val){
      if(val==1){
        return '启用'
      }else if(val == 0){
        return '禁用'
      }
    },
  },
  methods:{
    syncData(){
      this.syncLoading = true
      syncMaterialClass().then(()=>{
        this.syncLoading = false
        this.$message.success('同步成功')
      }).catch(()=>{
        this.syncLoading = false
        this.$message.error('同步失败')
      })
    },
    handleClose(){
      this.dialogVisible = false
    },
    handleConfirm(){
      const data = JSON.parse(JSON.stringify(this.sendForm))
      this.$refs.sendForm.validate(valid=>{
        if(valid){
          this.btnLoading= true
          saveCategory(data).then(res=>{
            Message.success('提交成功')
            this.getListData()
            this.dialogVisible = false
            this.btnLoading= false
          }).catch(()=>{
            this.btnLoading= false
          })
        }
      })
    },
    showPop(type,item){
      this.sendForm= JSON.parse(JSON.stringify(defaultSendForm))
      if (item) {
        this.dialogVisible = true;
        for (let key in defaultSendForm) {
          this.sendForm[key] = item[key] || item[key] == 0 ? item[key] : defaultSendForm[key];
        }
      }else{
        this.dialogVisible = true;
      }
      materialClassTree({categoryName:''}).then((res)=>{
        this.categoryList = res
      })
    },
    changeState(item){
      let data = {}
      for (let key in defaultSendForm) {
        data[key] = item[key]
      }
      data.isEnable = data.isEnable ? 0 : 1;
      saveCategory(data).then(res=>{
        this.getListData()
        this.$message.success('设置成功')
      })
    },
    handleClose2(){
      this.dialogVisible2 = false
    },
    handleConfirm2(){
      const data = JSON.parse(JSON.stringify(this.sendForm2))
      this.$refs.sendForm2.validate(valid=>{
        if(valid){
          this.btnLoading2=true
          saveBrand(data).then(res=>{
            Message.success('提交成功')
            this.getListData()
            this.dialogVisible2 = false
            this.btnLoading2=false
          }).catch(()=>{
            this.btnLoading2= false
          })
        }
      })
    },
    showPop2(type,item){
      this.sendForm2= JSON.parse(JSON.stringify(defaultSendForm2))
      if (item) {
        this.dialogVisible2 = true;
        for (let key in defaultSendForm2) {
          this.sendForm2[key] = item[key] || item[key] == 0 ? item[key] : defaultSendForm2[key];
        }
      }else{
        this.dialogVisible2 = true;
      }
    },
    changeState2(item){
      let data = {}
      for (let key in defaultSendForm2) {
        data[key] = item[key]
      }
      data.isEnable = data.isEnable ? 0 : 1;
      saveBrand(data).then(res=>{
        this.getListData()
        this.$message.success('设置成功')
      })
    },


    //获取品类列表
    getListData(){
      if(this.type =='goodsName'){
        const data = JSON.parse(JSON.stringify(this.listQuery))
        this.listLoading = true
        materialClassTree(data).then(res=>{
          this.gridOptions.data = res
          // this.$refs.xGrid.setTreeExpand(res, true)
          this.listLoading = false
        })
      }else if(this.type== 'brandName'){
        const data = JSON.parse(JSON.stringify(this.listQuery2))
        this.listLoading2 = true
        getBrandList(data).then(res=>{
          this.gridOptions2.data = res.list
          this.count2 = res.count
          this.listLoading2 = false
        })
      }
    },


    handleSearchList(){
      this.listQuery2.pageNum = 1;
      this.getListData();
    },
    handleSizeChange2(val){
      this.listQuery2.pageNum = 1;
      this.listQuery2.pageSize = val;
      this.getListData();
    },
    handleCurrentChange2(val){
      this.listQuery2.pageNum = val;
      this.getListData();
    },
    /**
     * 切换选择状态
     */
    async handleSelect(key, keyPath){
      this.type = key
      this.getListData()
    },


  },
}
</script>

<style lang="scss">
.vxe-table--render-default .vxe-tree--btn-wrapper{
  font-size: 14px;

}
.table-row:first-child{
  border-top: 1px solid #ddd;
}
.table-row{
  border: 1px solid #ddd;
  border-top:0;
}
.table-col{
  padding:2px 10px;

}
.table-col:first-child{
  border-right:1px solid #ddd;
  background: #f2f2f2;
  font-weight: bold;

}
</style>
